<template>
  <div class="create-activity">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">创建活动</h1>
        <p class="page-subtitle">发布新的校园活动，吸引更多学生参与</p>
      </div>
    </div>

    <!-- 创建表单 -->
    <el-card class="form-card">
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityFormRules"
        label-width="120px"
        size="large"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="活动名称" prop="title">
                <el-input
                  v-model="activityForm.title"
                  placeholder="请输入活动名称"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="活动类型" prop="type">
                <el-select v-model="activityForm.type" placeholder="请选择活动类型" style="width: 100%">
                  <el-option label="学术讲座" value="lecture" />
                  <el-option label="文艺演出" value="performance" />
                  <el-option label="体育竞技" value="sports" />
                  <el-option label="社会实践" value="practice" />
                  <el-option label="志愿服务" value="volunteer" />
                  <el-option label="技能培训" value="training" />
                  <el-option label="社团活动" value="club" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="活动状态" prop="status">
                <el-select v-model="activityForm.status" placeholder="请选择活动状态" style="width: 100%">
                  <el-option label="草稿" value="draft" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已发布" value="published" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="活动描述" prop="description">
            <el-input
              v-model="activityForm.description"
              type="textarea"
              :rows="4"
              placeholder="请详细描述活动内容、目的和意义"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 时间地点 -->
        <div class="form-section">
          <h3 class="section-title">时间地点</h3>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="activityForm.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="activityForm.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="活动地点" prop="location">
            <el-input
              v-model="activityForm.location"
              placeholder="请输入活动地点"
              maxlength="200"
            />
          </el-form-item>
        </div>

        <!-- 报名设置 -->
        <div class="form-section">
          <h3 class="section-title">报名设置</h3>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="报名人数" prop="maxParticipants">
                <el-input-number
                  v-model="activityForm.maxParticipants"
                  :min="1"
                  :max="10000"
                  placeholder="最大报名人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="报名开始" prop="registrationStart">
                <el-date-picker
                  v-model="activityForm.registrationStart"
                  type="datetime"
                  placeholder="报名开始时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="报名截止" prop="registrationEnd">
                <el-date-picker
                  v-model="activityForm.registrationEnd"
                  type="datetime"
                  placeholder="报名截止时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="报名要求">
            <el-input
              v-model="activityForm.requirements"
              type="textarea"
              :rows="3"
              placeholder="请输入报名要求和注意事项（可选）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 其他设置 -->
        <div class="form-section">
          <h3 class="section-title">其他设置</h3>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input
                  v-model="activityForm.contactPerson"
                  placeholder="请输入联系人姓名"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="activityForm.contactPhone"
                  placeholder="请输入联系电话"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="活动标签">
            <el-select
              v-model="activityForm.tags"
              multiple
              filterable
              allow-create
              placeholder="请选择或输入活动标签"
              style="width: 100%"
            >
              <el-option label="学术" value="academic" />
              <el-option label="文艺" value="art" />
              <el-option label="体育" value="sports" />
              <el-option label="科技" value="technology" />
              <el-option label="创新" value="innovation" />
              <el-option label="公益" value="charity" />
              <el-option label="社交" value="social" />
              <el-option label="职业" value="career" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="活动图片">
            <el-upload
              v-model:file-list="activityForm.imageList"
              action="/api/upload"
              list-type="picture-card"
              :limit="5"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              建议上传活动相关图片，支持jpg、png格式，单张图片不超过2MB
            </div>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="resetForm">重置</el-button>
          <el-button size="large" @click="saveDraft" :loading="saving">保存草稿</el-button>
          <el-button type="primary" size="large" @click="submitActivity" :loading="submitting">
            提交审核
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()
const activityFormRef = ref()
const saving = ref(false)
const submitting = ref(false)

const activityForm = reactive({
  title: '',
  type: '',
  status: 'draft',
  description: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 50,
  registrationStart: '',
  registrationEnd: '',
  requirements: '',
  contactPerson: '',
  contactPhone: '',
  tags: [],
  imageList: []
})

const activityFormRules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 5, max: 100, message: '活动名称长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' },
    { min: 20, max: 1000, message: '活动描述长度在 20 到 1000 个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入报名人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '报名人数至少为1', trigger: 'blur' }
  ],
  registrationStart: [
    { required: true, message: '请选择报名开始时间', trigger: 'change' }
  ],
  registrationEnd: [
    { required: true, message: '请选择报名截止时间', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const validateTimes = () => {
  const { startTime, endTime, registrationStart, registrationEnd } = activityForm
  
  if (startTime && endTime && new Date(startTime) >= new Date(endTime)) {
    ElMessage.error('活动结束时间必须晚于开始时间')
    return false
  }
  
  if (registrationStart && registrationEnd && new Date(registrationStart) >= new Date(registrationEnd)) {
    ElMessage.error('报名截止时间必须晚于报名开始时间')
    return false
  }
  
  if (registrationEnd && startTime && new Date(registrationEnd) > new Date(startTime)) {
    ElMessage.error('报名截止时间不能晚于活动开始时间')
    return false
  }
  
  return true
}

const resetForm = () => {
  activityFormRef.value?.resetFields()
  Object.assign(activityForm, {
    title: '',
    type: '',
    status: 'draft',
    description: '',
    startTime: '',
    endTime: '',
    location: '',
    maxParticipants: 50,
    registrationStart: '',
    registrationEnd: '',
    requirements: '',
    contactPerson: '',
    contactPhone: '',
    tags: [],
    imageList: []
  })
}

const saveDraft = async () => {
  try {
    saving.value = true
    
    const activityData = {
      ...activityForm,
      status: 'draft',
      images: activityForm.imageList.map(item => item.url || item.response?.url).filter(Boolean)
    }
    
    await api.post('/organizer/activities', activityData)
    ElMessage.success('草稿保存成功')
    
    // 询问是否跳转到活动列表
    const action = await ElMessageBox.confirm('草稿已保存，是否跳转到活动管理页面？', '保存成功', {
      confirmButtonText: '跳转',
      cancelButtonText: '继续编辑',
      type: 'success'
    }).catch(() => 'cancel')
    
    if (action === 'confirm') {
      router.push('/organizer/activities')
    }
    
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

const submitActivity = async () => {
  try {
    await activityFormRef.value.validate()
    
    if (!validateTimes()) {
      return
    }
    
    submitting.value = true
    
    const activityData = {
      ...activityForm,
      status: 'pending',
      images: activityForm.imageList.map(item => item.url || item.response?.url).filter(Boolean)
    }
    
    await api.post('/organizer/activities', activityData)
    
    await ElMessageBox.alert('活动已提交审核，请等待管理员审核通过后发布。', '提交成功', {
      confirmButtonText: '确定',
      type: 'success'
    })
    
    router.push('/organizer/activities')
    
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const handlePictureCardPreview = (file) => {
  console.log('预览图片:', file)
}

const handleRemove = (file, fileList) => {
  console.log('移除图片:', file, fileList)
}

const handleUploadSuccess = (response, file, fileList) => {
  console.log('上传成功:', response, file, fileList)
}
</script>

<style scoped>
.create-activity {
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.form-card {
  padding: 20px;
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
}

.form-section:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
  display: inline-block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-activity {
    margin: 0 16px;
  }
  
  .form-card {
    padding: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-date-editor.el-input) {
  border-radius: 6px;
}

:deep(.el-upload--picture-card) {
  border-radius: 6px;
}
</style>